<template>
  <div class="index-box" ref="index">
    <el-row :gutter="10">
      <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
        <div class="search" ref="search">
          <el-form :inline="true" :model="searchForm" size="small" ref="searchForm" @submit.native.prevent class="demo-form-inline" id="searchBox">
            <el-form-item prop="activityNo">
                <el-input v-model="searchForm.activityNo" clearable placeholder="活动编号"></el-input>
            </el-form-item>
            <el-form-item prop="activityName">
                <el-input v-model="searchForm.activityName" clearable placeholder="活动名称"></el-input>
            </el-form-item>
            <el-form-item prop="supplierName">
                <el-input v-model="searchForm.supplierName" clearable placeholder="供应商名称"></el-input>
            </el-form-item>
            <el-form-item prop="activityTypeId">
              <el-select filterable clearable v-model="searchForm.activityTypeId" placeholder="活动类型">
                 <el-option :label="item.dictLabel" :value="item.dictCode" v-for="item in typeList"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="activityStatus">
              <el-select filterable clearable v-model="searchForm.activityStatus" placeholder="活动状态">
                  <el-option label="启用" value="1" ></el-option>
                  <el-option label="禁用" value="2" ></el-option>
              </el-select>
            </el-form-item>
           <!-- <el-form-item prop="createTime">
              <el-date-picker v-model="createTime" type="daterange" align="right" unlink-panels range-separator="至"
                start-placeholder="活动开始日期" end-placeholder="活动结束日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                :picker-options="pickerOptions">
              </el-date-picker>
            </el-form-item> -->

            <el-form-item class="clearfix">
              <el-button type="primary" @click="handleSearch()" icon="el-icon-search">搜索</el-button>
              <el-button icon="el-icon-refresh" size="small" @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="actionBtn" ref="actionBtn">
          <div class="actionBtnLeft">
             <el-button type="primary" @click="handleAdd()" size="small"  icon="el-icon-plus" v-has="'operatingTools:activityManagement:add'">创建活动</el-button>
            <!-- <el-button type="warning" @click="handleStopAll()" size="small"  icon="el-icon-video-pause" v-has="'operatingTools:activityManagement:stop'">批量停用</el-button> -->
          </div>
          <div class="actionBtnRight">
              <MyRefresh></MyRefresh>
          </div>
        </div>

        <div class="table" ref="table">
          <el-table :data="dataList" style="width: 100%;"  border :height="tableHeight"   stripe v-loading="loading">
            <el-table-column prop="activityNo" label="活动编号" v-if="!hideTableColumn.includes('activityConfigId')" width="210" align="center"></el-table-column>
            <el-table-column prop="activityName" label="活动名称" v-if="!hideTableColumn.includes('activityTypeName')" align="center"></el-table-column>
            <el-table-column prop="activityName" label="活动图片" v-if="!hideTableColumn.includes('activityTypeName')" align="center">
              <template slot-scope="scope">
                <el-image :src="scope.row.activityPicture" v-image-preview="scope.row.activityPicture" style="height: 60px;" fit="fill"></el-image>
              </template>
            </el-table-column>
            <el-table-column prop="activityTypeName" label="活动类型" v-if="!hideTableColumn.includes('name')" align="center"></el-table-column>
            <el-table-column prop="supplierName" label="供应商名称" v-if="!hideTableColumn.includes('name')" align="center"></el-table-column>
             <el-table-column prop="sortOrder" label="排序" v-if="!hideTableColumn.includes('name')" align="center"></el-table-column>
            <el-table-column prop="activityStatus" label="活动状态" v-if="!hideTableColumn.includes('type')" align="center" width="120">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.activityStatus=='1'">启用</el-tag>
                <el-tag v-else type="warning">禁用</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="操作"  width="150" v-if="!hideTableColumn.includes('active')" align="center" fixed="right">
              <template #default="scope">
                <div class="verticalBtn">
                  <el-button
                    size="medium"
                    type="text"
                    icon="el-icon-view"
                    @click="handleView(scope.row)"
                  >查看</el-button>
                  <el-button
                    size="medium"
                    type="text"
                    icon="el-icon-s-shop"
                    v-has="'operatingTools:activityManagement:admin'"
                    @click="handleAddShop(scope.row)"
                  >商品管理</el-button>
                  <el-button
                    size="medium"
                    type="text"
                    :icon="scope.row.activityStatus=='1'?'el-icon-video-pause':'el-icon-video-play'"
                    @click="handleActivityStop(scope.row)"
                    v-has="'operatingTools:activityManagement:stop'"
                    v-if="scope.row.status='1'"
                  >{{scope.row.activityStatus=='1'?'禁用':'启用'}}</el-button>
                  <el-button
                    size="medium"
                    type="text"
                    icon="el-icon-edit-outline"
                    @click="handleEdit(scope.row)"
                    v-has="'operatingTools:activityManagement:edit'"
                  >修改</el-button>

                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="page" ref="page">
           <MyPagination
              v-show="total"
             :total="total"
             :page.sync="searchForm.pageNum"
             :limit.sync="searchForm.pageSize"
             @pagination="dataInfo"
           />
        </div>
      </el-col>
    </el-row>
    <!-- 新增 -->
    <el-dialog :title="dialogTitle" width="700px" v-dialogDrag :visible.sync="addVisible" @close="addVisible = false" :close-on-click-modal="false">
      <el-form  :model="form" id="userDialog" status-icon :rules="rules" ref="form" label-position="right" >
       <el-form-item label="活动名称" prop="activityName" label-width="125px" >
          <el-input type="text" v-model="form.activityName" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="活动类型" prop="activityTypeId" label-width="125px">
           <el-select filterable clearable v-model="form.activityTypeId" style="width: 100%;">
              <el-option :label="item.dictLabel" :value="item.dictCode" v-for="item in typeList"></el-option>
           </el-select>
        </el-form-item>
        <el-form-item label="供应商名称" prop="supplierType" label-width="125px">

            <el-radio-group v-model="form.supplierType">
              <el-radio label="1">候鸟</el-radio>
              <el-radio label="2">好礼</el-radio>
              <el-radio label="3">好店</el-radio>
              <el-radio label="4">其他</el-radio>
            </el-radio-group>
             <el-input type="text" v-if="form.supplierType=='4'" v-model="form.supplierName" autocomplete="off" style="display: inline-block;width: 150px;margin-left:10px"></el-input>
          </el-form-item>
        <el-form-item label="折扣系数" prop="discount" label-width="125px" >
            <el-input type="number" v-model="form.discount" autocomplete="off" ></el-input>
        </el-form-item>
        <el-form-item label="活动图片" prop="activityPicture" label-width="125px" >
          <MyUpImg :imagePreview='form.activityPicture'  imageSize="chang" @change="imageChange($event, 'activityPicture')"></MyUpImg>
        </el-form-item>
        <el-form-item label="活动链接" prop="activityUrl" label-width="125px" >
          <el-input type="text" v-model="form.activityUrl" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder" label-width="125px" >
          <el-input type="number" v-model="form.sortOrder" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="时效设置" prop="validityFlag" label-width="125px" >
          <el-radio-group v-model="form.validityFlag">
            <el-radio label="1">长期有效</el-radio>
            <el-radio label="2">自定义</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="自定义时效" prop="time" label-width="125px" v-if="form.validityFlag=='2'">
          <el-date-picker v-model="time" type="daterange" align="right" unlink-panels range-separator="至" style="width: 100%;"
            start-placeholder="自定义时效开始日期" end-placeholder="自定义时效结束日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd"> </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="dialogTitle!='查看活动'">
        <el-button @click="addVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleActivitySubmit('form')" size="small" :loading="btnLoading">保 存</el-button>
      </div>
      </el-dialog>
      <!-- 商品管理 -->
      <el-dialog title="商品管理" width="1000px" v-dialogDrag :visible.sync="addShopVisible" @close="addShopVisible = false" :close-on-click-modal="false">
        <el-dialog width="600px" :title="innerTitleVisible" :visible.sync="innerVisible" append-to-body v-dialogDrag >
            <el-form  :model="addShopForm" id="userDialog" status-icon :rules="addShopRules" ref="addShopForm" label-position="right" >
             <el-form-item label="商品SPU" prop="goodsSpu" label-width="125px" >
                <el-input type="text" v-model="addShopForm.goodsSpu" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="商品类目ID" prop="categoryId" label-width="125px" >
                <el-input type="number" v-model="addShopForm.categoryId" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="商品类目" prop="categoryName" label-width="125px" >
                <el-input type="text" v-model="addShopForm.categoryName" autocomplete="off"></el-input>
              </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer" v-if="innerTitleVisible!='查看商品'">
              <el-button @click="innerVisible = false" size="small">取 消</el-button>
              <el-button type="primary" @click="handleActivityAddShopSubmit('addShopForm')" size="small" :loading="btnLoading">保 存</el-button>
            </div>
        </el-dialog>
        <div style="margin-bottom: 15px;display: flex;">
          <el-button type="primary" @click="handleActivityAddShop()" icon="el-icon-add" size="small">添加商品</el-button>
          <el-upload
            style="margin:0 15px"
            class="upload-demo"
            :action="actionUrl"
            :headers="header"
            :show-file-list="false"
            :data={activityConfigId:activityConfigId}
            :on-success="handleAvatarSuccess"
            accept=".xlsx">
            <el-button size="small" type="primary" >批量导入</el-button>
          </el-upload>
          <el-button type="danger" @click="handleDelt()" icon="el-icon-add" size="small">批量删除</el-button>
          <el-button type="text" @click="handleTemplateDown()" icon="el-icon-add" size="small">导入模板下载</el-button>
        </div>
        <el-table :data="activityShopList" style="width: 100%;"  border  @selection-change="handleSelectionChange"  stripe v-loading="activityShopLoading">
          <el-table-column type="selection"  width="55" ></el-table-column>
          <el-table-column  type="index" label="编号"  width="70" align="center"></el-table-column>
          <el-table-column prop="categoryId" label="商品ID"  align="center"></el-table-column>
          <el-table-column prop="categoryName" label="商品类目"  align="center"></el-table-column>
          <el-table-column prop="goodsSpu" label="商品SPU" align="center"></el-table-column>
          <el-table-column prop="name" label="操作"  width="200"  align="center" fixed="right">
            <template #default="scope">
              <div>
                <el-button
                  size="medium"
                  type="text"
                  icon="el-icon-view"
                  @click="handleActivityAddShopView(scope.row)"
                >查看</el-button>
                <el-button
                  size="medium"
                  type="text"
                  icon="el-icon-edit-outline"
                  @click="handleActivityAddShopEdit(scope.row)"
                >修改</el-button>
                <el-button
                  size="medium"
                  type="text"
                  icon="el-icon-delete-solid"
                  @click="handleDelt(scope.row)"
                >删除</el-button>

              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- <div slot="footer" class="dialog-footer" >
          <el-button @click="addShopVisible = false" size="small">取 消</el-button>
          <el-button type="primary" @click="handleActivitySubmit('form')" size="small" :loading="btnLoading">确 定</el-button>
        </div> -->
        </el-dialog>
  </div>
</template>

<script>
  import common from '@/api/api';
  import {
    getHnActivityList, houniaoActivityGoodsAddActivity, houniaoActivityGoodsUpdateActivity, houniaoActivityGoodsUpdateStatus, addActivityGoods, updateActivityGoods, ActivityBatchDelete, getActivityGoodsList, houniaoActivityGoodsImportData
  } from '@/api/getData'
  import option from '../../common/option.js';
  export default {
    data() {
      return {
        loading: false,
        btnLoading: false,
        inputLoading:false,
        createTime:[],
        sendTime:[],
        typeList:[],
        searchForm: {
          activityNo:'',
          activityName:'',
          supplierName:'',
          activityTypeId:'',
          activityStatus:'',

          pageNum: 1,
          pageSize: 20,
        },
        dataList:[],
        total: 0,
        tableColumn:[],
        hideTableColumn:[],/*自定义表格列需要隐藏的*/
        tableColumnType:'staffManagement',/*自定义表格列类型传参*/
        tableHeight:0,//table 高度
        dialogTitle:'',
        addVisible:false,
        form:{
          activityConfigId:'',
          activityName:'',
          supplierType:'',
          sortOrder:'',
          activityTypeId:'',
          activityTypeName:'',
          supplierName:"",
          activityUrl:'',
          activityPicture:'',
          discount:'',
          validityFlag:'1',
        },
        time:[],
        rules: {
         activityName: [{required: true, message: '请输入活动名称',trigger: 'blur'}],
         sortOrder: [{required: true, message: '请输入活动排序',trigger: 'blur'}],
         activityTypeId: [{required: true, message: '请选择活动类型',trigger: 'blur'}],
         supplierType: [{required: true, message: '请选择供应商',trigger: 'blur'}],
         activityPicture: [{required: true, message: '请上传活动图片',trigger: 'blur'}],
         activityUrl: [{required: true, message: '请输入活动链接',trigger: 'blur'}],
         discount: [{required: true, message: '请输入折扣系数',trigger: 'blur'}],
         validityFlag: [{required: true, message: '请选择时效设置',trigger: 'blur'}],
        },


        addShopVisible:false,
        activityShopList:[],
        activityShopLoading:false,

        innerVisible:false,
        addShopForm:{
          activityConfigId:'',
          id:'',
          categoryId:'',
          categoryName:'',
          goodsSpu:''
        },
        addShopRules: {
         categoryId: [{required: true, message: '请输入商品类目ID',trigger: 'blur'}],
         categoryName: [{required: true, message: '请输入商品类目',trigger: 'blur'}],
         goodsSpu: [{required: true, message: '请输入商品spu',trigger: 'blur'}]
        },
        multipleSelection:[],
        activityConfigId:"",
        actionUrl:common.apihost+"/goods/houniaoActivityGoods/importData",
        header:{
          AuthorizationMega:''
        },
        innerTitleVisible:''
      }
    },
    computed: {
      pickerOptions: () => {
        return option.pickerOptions;
      }
    },
    mounted() {
      this.header.AuthorizationMega = localStorage.getItem('bossAppToken');
      this.dataInfo();
      this.getSelect();
      this.$nextTick(() => {
          this.tableHeight = this.$refs.index.offsetHeight - this.$refs.search.offsetHeight - this.$refs.actionBtn.offsetHeight - this.$refs.page.offsetHeight - 55;
      })
    },
    methods: {
      imageChange(path, name) {
        this.form[name] = path
      },
      handleTemplateDown(){
        const a = document.createElement('a')
        a.href = 'https://qianzhi-mall.oss-cn-guangzhou.aliyuncs.com/excel/%E5%80%99%E9%B8%9F%E6%B4%BB%E5%8A%A8%E5%95%86%E5%93%81%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx';
        document.body.appendChild(a);
        a.click();
      },
      /** 单个或批量删除 **/
      handleDelt(row){
        let ids = [];
        if(row){
          ids = [row.id]
        }else{
          if(!this.multipleSelection.length){
            this.$modal.msgError("请先选中在批量删除");
            return;
          }else{
            ids = [];
            for(let i=0;i<this.multipleSelection.length;i++){
              ids.push(this.multipleSelection[i].id)
            }
          }
        }
        this.$confirm(`您确定要删除商品SPU为${ids.join(',')}吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          ActivityBatchDelete({goodsIds:ids.join(',')}).then((result) => {
            if (result.code == '200') {
                 this.activityShopListFn();
                 this.$message({
                   message: result.msg,
                   type: 'success'
                 });
             }else{
                this.$message.error(result.msg);
             }
         });
        }).catch((err) => {
            console.log(err);
        });
      },
      handleActivityAddShopEdit(row){
        this.addShopForm = {
          activityConfigId:this.activityConfigId,
          id:row.id,
          categoryId:row.categoryId,
          categoryName:row.categoryName,
          goodsSpu:row.goodsSpu
        };
        this.innerTitleVisible = '修改商品'
        this.innerVisible = true;
      },
      handleActivityAddShopView(row){
        this.addShopForm = {
          activityConfigId:this.activityConfigId,
          id:row.id,
          categoryId:row.categoryId,
          categoryName:row.categoryName,
          goodsSpu:row.goodsSpu
        };
        this.innerTitleVisible = '查看商品'
        this.innerVisible = true;
      },
      handleAvatarSuccess(res, file) {
        if(res.code==200){
          this.activityShopListFn();
          this.$message.success(res.msg);
        }else{
          this.$message.error(res.msg)
        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      handleActivityAddShop(){
        this.addShopForm = {
          id:'',
          activityConfigId:this.activityConfigId,
          categoryId:'',
          categoryName:'',
          goodsSpu:''
        };
         this.innerTitleVisible = '新增商品'
        this.innerVisible = true;
      },
      handleActivityAddShopSubmit(formName){
        this.$refs[formName].validate(async(valid) => {
          if (valid) {
            this.btnLoading = true;
            let result;

            if(this.addShopForm.id){
              result = await updateActivityGoods(this.addShopForm);
            }else{
              result = await addActivityGoods(this.addShopForm);
            }
            if (result.code == 200) {
              this.$message.success(result.msg);
              this.innerVisible = false;
              this.activityShopListFn();
            } else {
              this.$message.error(result.msg);
            }
            this.btnLoading = false;

          }
        })
      },
      async activityShopListFn(){
        try {
          this.activityShopLoading = true;
           const result = await getActivityGoodsList({activityConfigId:this.activityConfigId});
            if (result.code == 200) {
              this.activityShopList = result.data;
            } else {
              this.$message.error(result.msg);
            }
             this.activityShopLoading = false;
        } catch (err) {
          this.activityShopLoading = false;
          console.log(err)
        }
      },
      resetSearch(){
        this.createTime = [];
        this.sendTime = [];
        this.resetForm('searchForm');
        this.dataInfo();
      },
      getSelect(){
        this.getSelectList('houniao_activity_type').then((res)=>{
          this.typeList = res.data;
        })
      },
      async dataInfo() {
        try {
          let data = this.addDateRange(this.searchForm, this.createTime, 'createTimeStart', 'createTimeEnd');
          data = this.addDateRange(this.searchForm, this.sendTime, 'giveTimeStart', 'giveTimeEnd');
          this.loading = true;
          const result = await getHnActivityList(data);
          if (result.code == 200) {
            this.total = result.total;
            this.dataList = result.rows;
          } else {
            this.$message.error(result.msg);
          }
          this.loading = false;
        } catch (err) {
          this.loading = false;
          console.log(err)
        }
      },
      handleActivityStop(row){
        this.$confirm(`您确定${row.activityStatus=='1'?'禁用':'启用'}吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          houniaoActivityGoodsUpdateStatus({activityConfigId:row.activityConfigId,activityStatus:row.activityStatus=='1'?'2':'1' }).then((result) => {
            if (result.code == '200') {
                 this.dataInfo();
                 this.$message({
                   message: result.msg,
                   type: 'success'
                 });
                 this.addVisible = false;
             }else{
                this.$message.error(result.msg);
             }
         });
        }).catch((err) => {
            console.log(err);
        });
      },
      handleAddShop(row){
        this.activityConfigId = row.activityConfigId;
        this.activityShopListFn();
        this.addShopVisible = true;

      },
      /** 新增活动类型 **/
      handleActivitySubmit(formName) {
        this.$refs[formName].validate(async(valid) => {
          if (valid) {
            this.btnLoading = true;
            for(let i=0;i<this.typeList.length;i++){
              if(this.form.activityTypeId==this.typeList[i].dictCode) this.form.activityTypeName = this.typeList[i].dictLabel;
            }
            let result;
            let data = this.addDateRange(this.form, this.time, 'validityStartDate', 'validityEndDate');
            if(this.form.activityConfigId){
              result = await houniaoActivityGoodsUpdateActivity(data);
            }else{
              result = await houniaoActivityGoodsAddActivity(data);
            }

            if (result.code == 200) {
              this.$message.success(result.msg);
              this.addVisible = false;
              this.dataInfo();
            } else {
              this.$message.error(result.msg);
            }
            this.btnLoading = false;

          }
        })
      },
      handleSearch() {
        this.searchForm.pageNum= 1;
        this.dataInfo();
      },
      handleView(row){
        this.$router.push({
        	path: '/operatingTools/activityManagementAdd',
        	query: {
        		type: 'view'
        	}
        });
      },
      handleAdd(){
        this.dialogTitle = '创建活动';
        this.form = {
          activityConfigId:'',
          activityName:'',
          sortOrder:'',
          activityTypeId:'',
          activityTypeName:'',
          supplierName:"",
          supplierType:"1",
          discount:'',
          activityPicture:'',
          activityUrl:'',
          validityFlag:'1'
        };
        this.addVisible = true;
      },
      handleEdit(row){
        this.dialogTitle = '修改活动';
        this.form = {
          activityConfigId:row.activityConfigId,
          activityName:row.activityName,
          sortOrder:row.sortOrder,
          activityTypeId:row.activityTypeId+'',
          activityTypeName:row.activityTypeName,
          supplierName:row.supplierName,

          discount:row.discount,
          activityPicture:row.activityPicture,
          activityUrl:row.activityUrl,
          supplierType:row.supplierType+'',
          validityFlag:row.validityFlag+'',

        };
        if(row.validityEndDate){
          this.time = [row.validityStartDate,row.validityEndDate]
        }
        this.addVisible = true;
      },
      handleView(row){
        this.dialogTitle = '查看活动';
        this.form = {
          activityConfigId:row.activityConfigId,
          activityName:row.activityName,
          sortOrder:row.sortOrder,
          activityTypeId:row.activityTypeId+'',
          activityTypeName:row.activityTypeName,
          supplierName:row.supplierName,
          discount:row.discount,
          activityPicture:row.activityPicture,
          activityUrl:row.activityUrl,
          supplierType:row.supplierType+'',
          validityFlag:row.validityFlag+'',
        };
        if(row.validityEndDate){
          this.time = [row.validityStartDate,row.validityEndDate]
        }
        this.addVisible = true;
      },
      /** 表格选中状态改变 **/
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },

    }
  }
</script>

<style scoped lang="scss">

  .title{
    text-align: center;
    margin:5px 0;
  }
  .el-table .el-dropdown-link{
      cursor: pointer;
      color: #61997A;
      margin-left: 5px;
  }
    .leftDialog{
      height:540px;
      overflow-y: auto;
    }
    .activeVerticalBox .activeItem{
      color:#61997A;
      cursor: pointer;
      margin: 0px;
      text-align: center;
      height:20px;
      line-height: 20px;
    }
    .activeVerticalBox .el-dropdown{
      display: flex;
      justify-content: center;
      color:#61997A;
      cursor: pointer;
    }
    .activeCheckedBox{
      border-top: 1px solid #ddd;
      padding:10px;
      height:52px;
      .el-tag{
        margin-right:10px;
      }
    }

</style>
